<?php

use Illuminate\Database\Seeder;
use App\Models\Product;
use App\Models\ProductSku;
use Carbon\Carbon;

class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $products = factory(Product::class,30)->create();

        foreach($products as $product){
            // 创建3个sku ,并且每个sku 的product_id 字段都设为当前循环的商品id
            $skus = factory(ProductSku::class)->times(3)->make()->each(function($sku,$index) use($product){
                $sku->product_id = $product->id;
                $sku->created_at = Carbon::now()->toDateTimeString();
                $sku->updated_at = Carbon::now()->toDateTimeString();
            });
            // \Log::info( $skus->toArray() );


            ProductSku::insert($skus->toArray());
            // 找出价格最低的sku 价格，把商品价格设置为该价格
            $product->price = $skus->min('price');
            $product->save();

        }
    }
}
